package org.example.controller;



import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.example.ai.result.Result;
import org.example.ai.result.ResultCodeEnum;
import org.example.ai.util.AuthContextHolder;
import org.example.login.RedisTokenLookup;
import org.example.mapper.UsersMapper;
import org.example.service.IUsersService;
import org.example.users.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-01-17
 */
@RestController
@RequestMapping("/users")
@Slf4j
@CrossOrigin
public class UsersController {
    @Autowired
    private IUsersService usersService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 用户登录判断是否存在账号不存在跳转注册页面 String phone
     * @param
     * @return
     */
    @Operation(summary = "用户登录")
    @PostMapping("/loginUser")
    public Result<String> loginUser(String phone,String code){
        System.out.println("phone:"+phone);
//        String codetwo = redisTemplate.opsForValue().get(phone);
//        if (codetwo==null){
//            return Result.fail("验证码已过期");
//        }
//        if(codetwo.equals(code)){
//            return Result.ok(usersService.loginUser(phone));
//        }else {
//            return Result.fail("验证码错误");
//        }
        return Result.ok(usersService.loginUser(phone));

    }
    @Operation(summary = "查看微服务是否可以运行调用")
    @PostMapping("/look")
    @RedisTokenLookup
    public Result<String> look(String app){
        Long id = AuthContextHolder.getUserId();
        String a =  "可以看到数据吗id="+id+"------"+app;
        return Result.ok(a);
    }

    @Operation(summary = "验证码发送")
    @GetMapping("/getVerifyCode")
    public Result<String> getVerifyCode( String phone){
        return Result.ok(usersService.getVerifyCode(phone));
    }


    @Autowired
    private UsersMapper usersMapper;

    @Operation(summary = "用户token是否失去效果如果没有失去效果就跳转并显示用户数据")
    @GetMapping("/getToken")
    public Result<Users> getToken(String token){
//        log.info("token:"+token);
        String userid = redisTemplate.opsForValue().get(token);
        org.example.users.pojo.Users users = usersMapper.selectById(userid);
        if (userid != null){
            return Result.build(users, ResultCodeEnum.SUCCESS.getCode(),"成功登录");
        }else {
            return Result.build(users, ResultCodeEnum.FAIL.getCode(),"登陆失败");
        }
    }

    @PostMapping("/UpdateenergyValue")
    public Result<Users> UpdateenergyValue(Integer id,Integer energyValue){
        Users users = usersMapper.selectById(id);
        users.setEnergyValue(energyValue);
        usersMapper.updateById(users);
        return Result.ok(users);
    }
}


